package com.casework

import grails.converters.JSON

class FirmController {
    static scaffold = true

    def create = {
        def caseId = params.remove('caseId')
        def firmInstance = new Firm()
        firmInstance.properties = params
        return [firmInstance: firmInstance, caseId: caseId]
    }

    def save = {
        def firmInstance = new Firm(params)
        def legalCase = LegalCase.get(params.caseId)

        if (firmInstance.save(flush: true)) {
            if (legalCase) {
                LegalCaseFirm.create(legalCase, firmInstance, true)
                redirect action:'show', id: legalCase.id, controller: 'legalCase'
                return
            }
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'firm.label', default: 'Firm'), firmInstance.id])}"
            redirect(action: "show", id: firmInstance.id)
        }
        else {
            render(view: "create", model: [firmInstance: firmInstance])
        }
    }

    def show = {
        def firmInstance = Firm.get(params.id)

        if (!firmInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'firm.label', default: 'Firm'), params.id])
            redirect(action: "list")
        }
        else {
            def legalCases = LegalCaseFirm.findAllByFirm(firmInstance).collect { it.legalCase } as Set
            [firmInstance: firmInstance, legalCases: legalCases]
        }
    }

    def allActiveFirms = {
        def paramName = params.term ? params.term.split(', ').last(): ''

        def criteria = LegalCaseFirm.createCriteria()
        def activeFirms = criteria.listDistinct  {
            projections {
                property 'firm'
            }
            cache true
        }
        def names = activeFirms.findAll {it.name.toLowerCase().startsWith(paramName.toLowerCase())}.collect{it.name}
        render names as JSON
    }
}
